import time
import plugin
import config

import os
import sys
import util
from util import Service

import sqlite3


START = 1
STOP = 2
QUIT = 3

class PluginService(Service):
    def __init__(self):
        Service.__init__(self)

        self.GET_ALL_PLUGINS = "get_all_plugins"
        self.ADD_PLUGIN = "add_plugin"
        self.REMOVE_PLUGIN = "remove_plugin"
        self.GET_PLUGIN_COUNT = "get_plugin_count"

    def describe(self, service):
        if service == self.GET_ALL_PLUGINS:
            return "Returns a list of all plugins"
        if service == self.ADD_PLUGIN:
            return '''
            Adds a plugin to the plugins database
            Parameters: plugin_name
        '''
        if service == self.REMOVE_PLUGIN:
            return '''
            Removes a plugin from the plugins database
            Parameters: plugin_name
            '''
        if service == self.GET_PLUGIN_COUNT:
            return "Returns the count of plugins"



    def get_all_plugins(self):
        conn = sqlite3.connect(os.path.expanduser(os.path.join("~","db","plugins.db")))
        c = conn.cursor()
        c.execute("select * from plugins")
        r = [x for x in c]
        c.close()
        return r
        

    def get_plugin_count(self):
        conn = sqlite3.connect(os.path.expanduser(os.path.join("~","db","plugins.db")))
        c = conn.cursor()
        c.execute("select count(*) from plugins")
        r = c.fetchone()[0]
        c.close()
        return r

    def services(self):
        result = []
        result.append(self.GET_ALL_PLUGINS)
        result.append(self.GET_PLUGIN_COUNT)
        result.append(self.ADD_PLUGIN)
        result.append(self.REMOVE_PLUGIN)
        return result

def service(service_name):
    return rmi.RMIService.service(service_name)

def register_service(service_name, service_instance):
    print "Registering service : ",service_name
    rmi.RMIService.register_service(service_name, service_instance)


def start_plugin_service():
    print "Starting plugin service.."
    register_service("plugins", PluginService())

def load_plugins(server,
                 service,
                 plugins_folder,
                 container = None,
                 should_wait = False):
    
    if container is not None:
        container.add_child(service.name)
    plugin.load_all(server,service, plugins_folder)
    service.start()

def connect_child_and_parent(parent,child):
    if parent is not None:
        parent.add_child(child)
        child.set_parent(parent)


if __name__ == "__main__":
    print "Starting plugin registry service"
    
                                       

                                   


